import axios from 'axios'
import { removeToken } from '@/utils/auth'
import { Toast } from 'vant'

// 创建axios实例
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
  baseURL: 'http://gem.com/api/v1/',
  // baseURL: 'http://gemback.12806.cn/api/v1/',
  timeout: 5000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return response.data
    } else {
      Toast(response.data.message)
      removeToken()
      location.reload() // 为了重新实例化vue-router对象 避免bug
      return Promise.reject(response.data.message)
    }
  },
  error => {
    console.log('err' + error) // for debug
    Toast(error.response.data.message)
    return Promise.reject(error)
  }
)

export default service
